import { Client, Databases, ID, Query } from 'appwrite';

const PROJECT_ID = import.meta.env.VITE_APPWRITE_PROJECT_ID;
const DATABASE_ID = import.meta.env.VITE_APPWRITE_DATABASE_ID;
const COLLECTION_ID = import.meta.env.VITE_APPWRITE_COLLECTION_ID;

const client = new Client()
  .setEndpoint('https://cloud.appwrite.io/v1')
  .setProject(PROJECT_ID);

const database = new Databases(client);

type MovieForm = {
  id: number;
  poster_path: string;
};

type MovieView = Document & {
  searchTerm: string;
  count: number;
  poster_url: string;
  movie_id: number;
};

export const updateSearchCount = async (
  searchTerm: string,
  movie: MovieForm,
) => {
  // console.log('movie', movie);

  const searchTermTrimeed = searchTerm.trim();
  // 1. Use Appwrite SDK to check if the search term exists in the database
  const result = await database.listDocuments(DATABASE_ID, COLLECTION_ID, [
    Query.equal('searchTerm', searchTermTrimeed),
  ]);

  // 2. If it does, update the count
  if (result.documents.length > 0) {
    const doc = result.documents[0];

    await database.updateDocument(DATABASE_ID, COLLECTION_ID, doc.$id, {
      count: doc.count + 1,
    });
  }
  // 3. If it doesn't, create a new document with the search term and count as 1
  else {
    const poster_url = movie.poster_path
      ? `https://image.tmdb.org/t/p/w500${movie.poster_path}`
      : '/no-movie.png';
    await database.createDocument(DATABASE_ID, COLLECTION_ID, ID.unique(), {
      searchTerm: searchTermTrimeed,
      count: 1,
      movie_id: movie.id,
      poster_url,
    });
  }
};

export const getTrendingMovies = async () => {
  const result = await database.listDocuments(DATABASE_ID, COLLECTION_ID, [
    Query.limit(5),
    Query.orderDesc('count'),
  ]);
  return result.documents as unknown as MovieView[];
};
